// pages/home_index/home_index.js
const sys = wx.getSystemInfoSync()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    banner:[{ id:0, image:  '../../images/header.jpeg'}],
    duration: 2000,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    loading: false, 
    imgUrls: [
      '../../images/header.jpeg',
    ],
    consult_text:"锵洋文字识别小工具简介--联系我们",
    add_news_file:"+ 添加新识别任务",
    filelist:[],//{index:1,name:"1.doc"}, {index:2,name:"2.doc"}, {index:3,name:"3.doc"},{index:4,name:"4.doc"}, {index:5,name:"5.doc"}, {index:6,name:"6.doc"},{index:7,name:"7.doc"}, {index:8,name:"8.doc"}
    item_height:0,
    canAddFile:true,
    isAppendText:false, //是否继续添加文字按钮
    modalHidden: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this 
    wx.showLoading({
      title: '请稍等',
      
    })
    setTimeout(function(){
      const openid = wx.getStorageSync('openid')  
      if(openid == ""|| openid == undefined){
          wx.showModal({
            title: '温馨提示',
            content: 'openid获取错误,请您重新打开小程序',
            complete: (res) => {
              if (res.cancel) {
                that.reGetOpenid()
              }
          
              if (res.confirm) {
                 that.reGetOpenid()
              }
            }
          })

          return
      }
     
      wx.request({
        method:"POST",
        //url: 'http://121.37.180.71:8002/getExsitFiles',
        url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
        header: {
          'content-type': 'application/json' 
        },       
        data:{
          openid:openid
        },
        success:function(res){
           //["doc1", "doc1.docx"]
          wx.hideLoading()
          let data_arr = res.data
          let tmp_content = []
          data_arr.forEach(function(value,index){          
            let tmp_item = {id:index+1, name:value}
            tmp_content.push(tmp_item)
          })
          that.setData({
            filelist:tmp_content
          })
  
          if(data_arr.length == 8){          
            that.setData({
              canAddFile:false, /**满8个不能添加 新文件 */
              add_news_file:"当前文档总数已满,请删除部分后再添加"
            })
          }else{
            that.setData({
              canAddFile:true,
              add_news_file:"+ 添加新识别任务",
            })
          }
        },
        fail:function(err){
          wx.hideLoading()
          console.log(err)
        }
      })
    },1000)

    //根据当前屏幕 计算每一行的高    
    let screenHeight = sys.windowHeight
    let everyLine = (screenHeight -40 -200 -10 -56 -10 -40 -30)/8
    that.setData({
      item_height:everyLine
    })
  },

  refresh_data:function(){
    let that = this 
    wx.showLoading({
      title: '请稍等',     
    })


    const openid = wx.getStorageSync('openid')  
    if(openid == ""|| openid == undefined){
        wx.showModal({
          title: '温馨提示',
          content: 'openid获取错误,请您重新打开小程序',
          complete: (res) => {
            if (res.cancel) {
              that.reGetOpenid()
            }
        
            if (res.confirm) {
               that.reGetOpenid()
            }
          }
        })

        return
    }
   
    wx.request({
      method:"POST",
      //url: 'http://121.37.180.71:8002/getExsitFiles',
      url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
      header: {
        'content-type': 'application/json' 
      },       
      data:{
        openid:openid
      },
      success:function(res){
         //["doc1", "doc1.docx"]
        wx.hideLoading()
        let data_arr = res.data
        let tmp_content = []
        data_arr.forEach(function(value,index){          
          let tmp_item = {id:index+1, name:value}
          tmp_content.push(tmp_item)
        })
        that.setData({
          filelist:tmp_content
        })

        if(data_arr.length == 8){          
          that.setData({
            canAddFile:false, /**满8个不能添加 新文件 */
            add_news_file:"当前文档总数已满,请删除部分后再添加"
          })
        }else{
          that.setData({
            canAddFile:true,
            add_news_file:"+ 添加新识别任务",
          })
        }
      },
      fail:function(err){
        wx.hideLoading()
        console.log(err)
      }
    })

  },
  addNewFile:function(){
    let that = this

    wx.request({
      method:"POST",
      // url: 'http://121.37.180.71:8002/getExsitFiles',
      url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
      header: {
        'content-type': 'application/json' 
      },       
      data:{
        openid:wx.getStorageSync('openid')
      },
      success:function(res){
         //["doc1", "doc1.docx"]
        let data_arr = res.data
        if(data_arr.length >= 8){
          wx.showModal({
            title: '提示',
            content: '文档已满，请删除部分再添加',
            success (res) {        
            }
          })
          return
        }else{      
          wx.navigateTo({
            //url: '../home/home?type=new',
            url: '../FunctionList/FunctionList?type=new',
          })    
        }     
      },
      fail:function(err){
        console.log(err)
      }
    })
  
  },

  /*打开文件并可以继续追加文字*/
  openfile(e){
    let that = this 
    let filename = e.currentTarget.dataset.name
    let openid = wx.getStorageSync('openid')
    wx.downloadFile({
      //url: "http://121.37.180.71:8002/static/tmp_docx/"+openid+"/"+filename, // 文件的本身url
      url: "https://admin.yzqysoft.com:8002/static/tmp_docx/"+openid+"/"+filename, // 文件的本身url
      filePath: wx.env.USER_DATA_PATH + '/'+filename, // 本地自定义的文件名
      success: function (res) {
        let filePath = res.filePath; // 微信临时文件路径(这里要使用自定义的名字文件名,否则打开的文件名是乱码)
        wx.openDocument({
          filePath: filePath,
          showMenu: true,  // 是否显示右上角菜单按钮 默认为false(看自身需求，可要可不要。后期涉及到右上角分享功能)
          success: function () {            
            wx.showToast({
              title: '打开文件成功',
            })
          },
          fail: function() {
            wx.showToast({ title: '打开文件失败，请稍后重试' });
          }
        });  
      }
    })
    // wx.navigateTo({
    //   url: '../preview/preview?filename='+filename
    // })

  },

  appendText(e){
    let that = this
    let filename = e.currentTarget.dataset.name

    wx.showModal({
      title: '追加文字',
      content: '您确认在'+filename+"继续追加文字",
      complete: (res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          wx.navigateTo({
            //url: '../home/home?type=append&filename='+filename,
            url: '../FunctionList/FunctionList?type=append&filename='+filename,
          })          
        }
      }
    })

    // wx.navigateTo({
    //   url: '../home/home',
    // })
  },

  delfile(e){
    let that = this
    let filename = e.currentTarget.dataset.name
    let openid = wx.getStorageSync('openid')
    wx.showModal({
      title: '重要提示',
      content: '您确定要删除'+filename+"文件吗,删除后不可恢复!",
      complete: (res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          wx.request({
            method:"post",
            header: {
              'content-type': 'application/json' 
            },
            //url: 'http://121.37.180.71:8002/delFile',
            url: 'https://admin.yzqysoft.com:8002/delFile',
            data:{
              filename:filename,
              openid:openid
            },
            success:(res)=>{
              wx.request({
                method:"POST",
                //url: 'http://121.37.180.71:8002/getExsitFiles',
                url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
                header: {
                  'content-type': 'application/json' 
                },       
                data:{
                  openid:wx.getStorageSync('openid')
                },
                success:function(res){
                   //["doc1", "doc1.docx"]
                  let data_arr = res.data
                  let tmp_content = []
                  data_arr.forEach(function(value,index){          
                    let tmp_item = {id:index+1, name:value}
                    tmp_content.push(tmp_item)
                  })
                  that.setData({
                    filelist:tmp_content
                  })
          
                  if(data_arr.length == 8){          
                    that.setData({
                      canAddFile:false, /**满8个不能添加 新文件 */
                      add_news_file:"当前文档总数已满,请删除部分后再添加"
                    })
                  }else{
                    that.setData({
                      canAddFile:true,
                      add_news_file:"+ 添加新文件",
                    })
                  }
                },
                fail:function(err){
                  console.log(err)
                }
              })


            }
          })          
        }
      }
    })

  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 去联系我们页面
   */
  gotoMap(){
    let that = this
    wx.navigateTo({
      url: '../ContactUS/contact',
    })

  },

  contact_us(){
    let that = this
    that.setData({
      modalHidden: false
    })
  },

  reGetOpenid(){
    let that = this

    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let that = this       
        if (res.code) {         
          wx.request({             
            method:"post",     
            url:'https://admin.yzqysoft.com:8002/getWXInfo',
            data: {
              appid:"wx2f6a5ce3765a80ae", //臻邦
              //appid:"wx34fa1743fa2c9078",
              code: res.code 
            },  
            header: {
              'content-type': 'application/json',
            },  
            success: res => {   
              //openid获取出错的情况
              if(res.data == "openid error"){
                wx.setStorageSync('openid', "")
                console.log("openid error")
                return
              }
              let openid = res.data
              wx.setStorageSync('openid', openid)
              
              if(openid!=undefined && openid != ""){
                //发送请求查看有没有 该用户对应的文件夹
                wx.request({
                  method:"POST",               
                  url:'https://admin.yzqysoft.com:8002/makeWXDir',
                  data: {
                    dirname:openid.toString(),
                  },  
                  header: {
                    'content-type': 'application/json',
                  },  
                  success:function(res){                
                     wx.request({
                        method:"POST",
                        //url: 'http://121.37.180.71:8002/getExsitFiles',
                        url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
                        header: {
                          'content-type': 'application/json' 
                        },       
                        data:{
                          openid:openid
                        },
                        success:function(res){
                           //["doc1", "doc1.docx"]
                          wx.hideLoading()
                          let data_arr = res.data
                          let tmp_content = []
                          data_arr.forEach(function(value,index){          
                            let tmp_item = {id:index+1, name:value}
                            tmp_content.push(tmp_item)
                          })
                          that.setData({
                            filelist:tmp_content
                          })
                  
                          if(data_arr.length == 8){          
                            that.setData({
                              canAddFile:false, /**满8个不能添加 新文件 */
                              add_news_file:"当前文档总数已满,请删除部分后再添加"
                            })
                          }else{
                            that.setData({
                              canAddFile:true,
                              add_news_file:"+ 添加新识别任务",
                            })
                          }
                        },
                        fail:function(err){
                          wx.hideLoading()
                          console.log(err)
                        }
                      })

                  },
                  fail:function(err){
                    console.log(err)
                  }
                })
              }else{
                console.log("openid==undefined || openid == \"\"")
              }              
            }
          })       
        }
      }
    })

  },

  /**
   * 点击取消
   */
  modalCandel: function() {
    this.setData({
         modalHidden: true
    })
  },
   
    /**
      *  点击确认
      */
  modalConfirm: function() {
    this.setData({
         modalHidden: true
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})